package com.gitee.web.stu.service;

import com.gitee.fastmybatis.core.ext.transaction.TransactionTemplateManager;
import com.gitee.fastmybatis.core.ext.util.MybatisUtil;
import com.gitee.fastmybatis.core.support.BaseService;
import com.gitee.web.config.Dbs;
import com.gitee.web.goods.entity.Goods;
import com.gitee.web.goods.mapper.GoodsMapper;
import com.gitee.web.goods.service.GoodsService;
import com.gitee.web.stu.entity.TUser;
import com.gitee.web.stu.mapper.TUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author thc
 */
@Service
public class UserService extends BaseService<TUser, Integer, TUserMapper>  {

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    GoodsService goodsService;

    @PostConstruct
    public void init() {
        Goods goods = goodsMapper.getById(1);
        System.out.println(goods);
    }

    /**
     * 主数据源事务
     * @param tUser
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(TUser tUser) {
        Goods goods = goodsMapper.getById(1);
        System.out.println(goods);
        int update = this.update(tUser);
        int i = 1 / 0;
        return update;
    }

    /**
     * 手动处理事务
     *
     * @param tUser
     * @return
     */
    public int updateUser2(TUser tUser) {
        return MybatisUtil.doTransaction(transactionStatus -> {
            int update = this.update(tUser);
            int i = 1 / 0;
            return update;
        });
    }

    /**
     * 手动处理事务,方式2
     *
     * @param tUser
     * @return
     */
    public int updateUser3(TUser tUser) {
        return Dbs.STU.doTransaction(status -> {
            int update = this.update(tUser);
            int i = 1 / 0;
            return update;
        });
    }

    public void updateAll(TUser tUser, Goods goods) {
        MybatisUtil.doTransactionNoResult("stu", status -> {
            this.update(tUser);
            int i = 1 / 0;
        });

        MybatisUtil.doTransactionNoResult( "goods", status -> {
            goodsService.update(goods);
            int i = 1 / 0;
        });
    }

}
